import { BadGatewayException, Body, Controller, Post, Req } from '@nestjs/common';
import { QudaobaoModel } from 'src/mongodb/models/qudaobaoModel/qudaobaoModel';
import { LanxiModel } from 'src/mongodb/models/lianxiModel/LanxiModel';
import { JihuoModel } from 'src/mongodb/models/jihuoModel/jihuoModel';
import { IdfaModel } from 'src/mongodb/models/idfaModel/idfa.models';
import { OperatService } from '../../operatApi/operat.service';
import { RedisdbService } from 'src/redis/redisdb.service';
import { ModelType } from '@typegoose/typegoose/lib/types';
import IP2Region, { IP2RegionResult } from "ip2region";
import { InjectModel } from 'nestjs-typegoose';
import * as crypto from 'crypto'

@Controller('index')
export class JihuoController {

    constructor(
        @InjectModel(LanxiModel) private readonly lianxi: ModelType<LanxiModel>,
        @InjectModel(JihuoModel) private readonly jihuo: ModelType<JihuoModel>,
        @InjectModel(QudaobaoModel) private readonly qudaobao: ModelType<QudaobaoModel>,
        private readonly operat: OperatService,
        private redis: RedisdbService
    ) { }


    /* 点击激活 */
    @Post('clickJihuo')
    async clickJihuo(@Body() body, @Req() req) {
        try {
            if (body.imei) {
                try {
                    const channelResult = await this.qudaobao.findOne({ mark: req.dns })
                    const md5 = crypto.createHash('md5');
                    const imeimd5 = md5.update(body.imei).digest('hex')
                    if (channelResult) {
                        /* web模式添加ip信息 */
                        if (channelResult.webmodel) {
                            let parse = JSON.parse(body.imei)
                            parse.ips = this.getip(req)
                            body.imei = JSON.stringify(parse)
                        }
                        /* 加白联调判断 */
                        if (!channelResult.whitelist) {
                            /* 查询数据库是否有该设备 */
                            const jihuoData = await this.jihuo.findOne({ ditch: req.dns, imeiMd5: imeimd5, type: 'jihuo' })

                            /* 判断数据库是否有该设备 */
                            if (!jihuoData) {
                                /* 统计渠道包激活次数 */
                                this.qudaobao.updateOne({ mark: req.dns }, { $inc: { todayjihuo: 1, totaljihuo: 1 } }).then()
                                let lianxi
                                /* 判断联系方式去重 */
                                /* 如果联系方式去重,则给该设备绑定一个唯一的联系方式,不去重则不绑定 */
                                if (channelResult.deduplication) {
                                    /* 查询该包号下面的联系方式 */
                                    lianxi = await this.lianxi.findOne({ mark: req.dns, status: true }).sort({ devnum: 1 })
                                    if (lianxi) {
                                        this.lianxi.updateOne({ _id: lianxi._id }, { $inc: { devnum: 1 } }).then()
                                    }
                                }
                                this.jihuo.create({
                                    ditch: req.dns,
                                    imeiMd5: imeimd5,
                                    imei: body.imei,
                                    visitorid: body.visitorId,
                                    platform: body.platform,
                                    createtime: Math.floor(Date.now() / 1000),
                                    type: 'jihuo',
                                    lianxi,
                                    userid: channelResult.userid,
                                    username: channelResult.username
                                }).then()

                                this.operat.methodFun(body, req, 'jihuo').then()
                            } else {
                                console.log('设备重复激活,包号' + req.dns + "---imei:" + JSON.stringify(body.imei));
                            }
                            // ================================================================
                            // ================================================================
                            /* 渠道屏蔽 */
                            if (channelResult.qudaohide) {
                                /* 判断 如果开启虚拟职位有url返回url */
                                if (channelResult.fake == 0 && channelResult.markurl) {
                                    return channelResult.markurl
                                }
                                // ================================================================
                                /* 判断屏蔽地区跳转url */
                                if (channelResult.qidu && channelResult.markurl) {
                                    const ipInstance = new IP2Region({ disableIpv6: false });
                                    const ipdetails: IP2RegionResult = ipInstance.search(this.getip(req));
                                    const cs = ipdetails.province + ipdetails.city
                                    const cityList = channelResult.qidu.split(',')
                                    for (let i = 0; i < cityList.length; i++) {
                                        const regProvince = new RegExp(cityList[i]);
                                        if (cs.match(regProvince)) {
                                            return channelResult.markurl
                                        }
                                    }
                                }
                                // ================================================================
                                let imeiData = JSON.parse(body.imei)
                                let result: IdfaModel
                                if (body.platform == 'android') {
                                    if (imeiData.oaid) {
                                        result = await this.redis.exists(imeiData.oaid.toLowerCase() + "_" + req.dns)
                                        if (!result) {
                                            if (imeiData.imei) await md5imei.call(this)
                                        }
                                    } else if (imeiData.imei) {
                                        await md5imei.call(this)
                                    }
                                    async function md5imei() {
                                        const imei: string[] = imeiData.imei.split(",")
                                        for (let item of imei) {
                                            const md5 = crypto.createHash('md5');
                                            result = await this.redis.exists(md5.update(item).digest('hex') + "_" + req.dns);
                                            if (result) break;
                                        }
                                    }
                                }
                                if (body.platform == 'ios') {
                                    if (imeiData.idfa) {
                                        result = await this.redis.exists(imeiData.idfa.toLowerCase() + "_" + req.dns)
                                    }
                                }

                                if (body.platform == 'web' && channelResult.webmodel) {
                                    if (imeiData.ips) {
                                        result = await this.redis.exists(imeiData.ips.toLowerCase() + "_" + req.dns)
                                    }
                                }
                                if (!result) {
                                    if (channelResult.markurl) {
                                        return channelResult.markurl
                                    }
                                }
                            }
                        } else {
                            await this.operat.methodFun(body, req, 'jihuo')
                            console.log('激活加白联调');
                        }
                    }
                } catch (error) {
                    console.log(error);
                    throw error
                }
            } else {
                console.log("激活异常" + JSON.stringify(body));
                throw '激活异常手机环境异常,请使用正规手机端打开app哟,或者重启app再试哟'
            }
        } catch (error) {
            console.log(error);
            throw new BadGatewayException(error)
        }
    }



    private getip(req): string {
        try {
            return (req.headers['x-wq-realip'] ||
                req.headers['X-Real-IP'] ||
                req.headers['x-forwarded-for'] ||
                req.connection.remoteAddress ||
                req.socket.remoteAddress ||
                req.connection.socket.remoteAddress ||
                req.ip).match(/\d+.\d+.\d+.\d+/)[0]
        } catch (e) {
            return "未知IP";
        }
    }
}

